package com.hjb.service.impl.recharge;

import com.hjb.service.domain.product.SiteUserBuy;
import com.hjb.service.domain.recharge.SiteUserRecharge;
import com.hjb.service.domain.recharge.SiteUserRechargeExample1;
import com.hjb.service.domain.siteuser.SiteUser;
import com.hjb.service.domain.siteuser.SiteUserExample;
import com.hjb.service.domain.siteuseraccount.SiteUserAccount;
import com.hjb.service.domain.siteuseraccount.SiteUserAccountExample;
import com.hjb.service.gateway.baofoo.BaoFooPayService;
import com.hjb.service.mapper.SiteUserAccountMapper;
import com.hjb.service.mapper.SiteUserMapper;
import com.hjb.service.mapper.SiteUserRechargeMapper;
import com.hjb.service.recharge.RechargeService;
import com.hjb.service.utils.DateUtil;
import com.hjb.service.utils.MapUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by gy on 2017/7/28.
 * 充值接口实现
 */
@Service
public class RechargeServiceImpl implements RechargeService {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaoFooPayService baoFooPayService;
	@Autowired
	private SiteUserMapper siteUserMapper;
	@Autowired
	private SiteUserRechargeMapper siteUserRechargeMapper;
	@Autowired
	private SiteUserAccountMapper siteUserAccountMapper;

	@Override
	public Map<String, Object> recharge(SiteUserBuy siteUserBuy) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			//查询用户账户信息
			SiteUserAccount siteUserAccount = new SiteUserAccount();
			SiteUserAccountExample example = new SiteUserAccountExample();
			example.createCriteria().andUserIdEqualTo(siteUserBuy.getUserId());
			List<SiteUserAccount> userAccountList =  siteUserAccountMapper.selectByExample(example);
			if (userAccountList == null || userAccountList.size() == 0){//无用户账户记录
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "无用户账户信息");
				return resMap;
			}
			//查询用户信息
			SiteUser siteUser = new SiteUser();
			SiteUserExample siteUserExample = new SiteUserExample();
			siteUserExample.createCriteria().andUserIdEqualTo(siteUserBuy.getUserId());
			List<SiteUser> siteUserList = siteUserMapper.selectByExample(siteUserExample);
			if (siteUserList == null || siteUserList.size() == 0){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "无用户信息");
				return resMap;
			}
			siteUser = siteUserList.get(0);
			//调取三方发送验证码
			Map<String, String> param = getRechargeParam(siteUserBuy,siteUser);
			Map<String, Object> dataMap = baoFooPayService.authPay(param);
			//业务处理
			if (dataMap == null){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "获取验证码失败,请重试");
				return resMap;
			}
			//插入充值记录信息 设置状态为充值中
//			SiteUserRecharge siteUserRecharge = getSiteUserRecharge(siteUserBuy,siteUser,siteUserAccount);
			SiteUserRecharge siteUserRecharge = null;
			if (siteUserRecharge == null){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "用户信息不全");
				return resMap;
			}
			siteUserRecharge.setRetCode(String.valueOf(dataMap.get("resp_code")));
			siteUserRecharge.setRetMsg(String.valueOf(dataMap.get("resp_msg")));
			siteUserRecharge.setTradeNo(String.valueOf(dataMap.get("business_no")));
			siteUserRecharge.setCallbackMsg(String.valueOf(dataMap.get("dataJson")));
			siteUserRechargeMapper.insertSelective(siteUserRecharge);
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			if ("0000".equals(siteUserRecharge.getRetCode())){
				resMap.put("result_code", MapUtil.INTF_SUC_CODE);
			}
			resMap.put("result_info", siteUserRecharge.getRetMsg());
		}catch (Exception e){
			log.info("获取验证码失败"+e);
			resMap.put("result_code",MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "获取验证码失败，请重试");
		}
		return resMap;
	}

	@Override
	public Map<String, Object> rechargeConfirm(SiteUserBuy siteUserBuy,String smsCode) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			if (siteUserBuy.getAmount() == null){
				resMap.put("result_code",MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "购买金额为空");
				return resMap;
			}
			if (new BigDecimal(0).compareTo(siteUserBuy.getAmount()) !=-1){//充值金额大于0
				resMap.put("result_code",MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "充值金额有误");
				return resMap;
			}
			//获取充值记录
			SiteUserRechargeExample1 example = new SiteUserRechargeExample1();
			String orderNo = siteUserBuy.getOrderNo();
			BigDecimal amount = siteUserBuy.getAmount();
			example.createCriteria().andOrderIdEqualTo(orderNo).andAmountEqualTo(amount).andStatusEqualTo(1);
			List<SiteUserRecharge> siteUserRechargeList = siteUserRechargeMapper.selectByExample(example);
			if (siteUserRechargeList == null || siteUserRechargeList.size() ==0){
				log.info("未查到处理中的充值记录，订单号："+orderNo +"充值金额："+amount);
				resMap.put("result_code",MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "未查到处理中的充值记录，订单号："+orderNo +"充值金额："+amount);
				return resMap;
			}
			SiteUserRecharge siteUserRecharge = siteUserRechargeList.get(0);
			//调取三方充值
			Map<String, String> param = new HashMap<String, String>();
			param.put("smsCode",smsCode);
			param.put("businessNo",siteUserRecharge.getTradeNo());
			Map<String, Object> dataMap = baoFooPayService.authPayConfirm(param);
			//业务处理
			if (dataMap == null){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "充值失败");
				return resMap;
			}
			siteUserRecharge.setRetCodeConf(String.valueOf(dataMap.get("resp_code")));
			siteUserRecharge.setRetMsgConf(String.valueOf(dataMap.get("resp_msg")));
			siteUserRecharge.setTradeNoConf(String.valueOf(dataMap.get("business_no")));
			siteUserRecharge.setCallbackMsgConf(String.valueOf(dataMap.get("dataJson")));
			siteUserRecharge.setReplyTime(new Date());
			siteUserRecharge.setStatus(1);
			siteUserRechargeMapper.updateByExample(siteUserRecharge,example);
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			if ("0000".equals(siteUserRecharge.getRetCode())){
				resMap.put("result_code", MapUtil.INTF_SUC_CODE);
			}
			resMap.put("result_info", siteUserRecharge.getRetMsg());
		}catch (Exception e){
			log.info("充值失败"+e);
			resMap.put("result_code",MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "请求失败");
		}
		return resMap;
	}

	/*@Override
	@Transactional
	public void rechargeQuery(SiteUserRecharge siteUserRecharge) {
		if (siteUserRecharge != null){
			Map<String, String> request = new HashMap<String, String>();
			request.put("origTransId", siteUserRecharge.getOrderIdConf());
			request.put("origTransDate", DateUtil.format(siteUserRecharge.getReplyTime(),"yyyyMMddHHmmss"));
			Map<String, Object> resultMap = baoFooPayService.authPayQuery(request);
			//业务处理
			if (resultMap == null){
				log.info("三方返回数据为空");
				return;
			}
			if ("0000".equals(String.valueOf(resultMap.get("resp_code")))){//调用成功
				dealRecharge(resultMap);
			}
		}
	}**/
	/*private SiteUserRecharge getSiteUserRecharge(SiteUserBuy siteUserBuy,SiteUser siteUser,SiteUserAccount siteUserAccount){
		SiteUserRecharge siteUserRecharge = new SiteUserRecharge();
		siteUserRecharge.setOrderId(siteUserBuy.getOrderNo());
		siteUserRecharge.setUserId(siteUserBuy.getUserId());
		siteUserRecharge.setAmount(siteUserBuy.getAmount());
		siteUserRecharge.setInitialAmount(siteUserAccount.getTotalRecharge());
		siteUserRecharge.setFinalAmount(siteUserBuy.getAmount().add(siteUserAccount.getTotalRecharge()));
		siteUserRecharge.setProductId(siteUserBuy.getProductId());
		siteUserRecharge.setInfo("用户："+siteUserBuy.getUserId()+" 购买产品："+siteUserBuy.getProductId()+" 金额："+siteUserBuy.getAmount()+" 元");
		siteUserRecharge.setStatus(0);
		siteUserRecharge.setCreateTime(new Date());
		siteUserRecharge.setType(1);
		siteUserRecharge.setBankCard(siteUser.getBankCardNo());
		return siteUserRecharge;
	}**/
	private Map<String, String> getRechargeParam(SiteUserBuy siteUserBuy,SiteUser siteUser){
		Map<String, String> param = new HashMap<String, String>();
		param.put("transId",siteUserBuy.getOrderNo());
		param.put("ip",siteUserBuy.getIp());
		param.put("amount",String.valueOf(siteUserBuy.getAmount()));
//		param.put("bindId",siteUser.getBindId());
		return param;
	}
	//处理业务
	/*private String dealRecharge(Map<String, Object> param){
		try {
			String orderNo = String.valueOf(param.get("orig_trans_id"));//订单号
			String message = String.valueOf(param.get("resp_msg"));//三方返回信息
			String dataJson = String.valueOf(param.get("dataJson"));//三方返回
			String code = String.valueOf(param.get("resp_code"));//三方返回码
			String status = String.valueOf(param.get("order_stat"));//三方返回状态
			BigDecimal amount = BigDecimal.valueOf(Long.parseLong(param.get("succ_amt").toString()));//交易金额

			if ("I".equals(status)){
				log.info("三方返回状态为处理中，不需处理业务");
				return null;
			}
			if ("FF".equals(status)){
				log.info("请求处理失败，不需处理业务");
				return null;
			}

			//1.获取充值记录
			SiteUserRechargeExample1 example = new SiteUserRechargeExample1();
			example.createCriteria().andOrderIdEqualTo(orderNo).andAmountEqualTo(amount).andStatusEqualTo(1);
			List<SiteUserRecharge> siteUserRechargeList = siteUserRechargeMapper.selectByExample(example);
			if (siteUserRechargeList == null || siteUserRechargeList.size() ==0){
				log.info("未查到处理中的充值记录，订单号："+orderNo +"充值金额："+amount);
				return null;
			}
			//2.判断是否处理充值记录 初期余额=用户账户表中累计充值金额
			SiteUserRecharge siteUserRecharge = siteUserRechargeList.get(0);
			//查询用户账户信息
			SiteUserAccountExample userAccountExample = new SiteUserAccountExample();
			userAccountExample.createCriteria().andUserIdEqualTo(siteUserRecharge.getUserId());
			List<SiteUserAccount> userAccountList =  siteUserAccountMapper.selectByExample(userAccountExample);
			if (userAccountList == null || userAccountList.size() == 0){//无用户账户记录
				log.info("未查到用户账户记录，userId："+siteUserRecharge.getUserId());
				return null;
			}

			SiteUserAccount siteUserAccount = userAccountList.get(0);
			BigDecimal initialAmount = siteUserRecharge.getInitialAmount();//期初金额
			BigDecimal totalRecharge = siteUserAccount.getTotalRecharge();//充值累计金额
			if (initialAmount.equals(totalRecharge)){
				//3.更新充值记录状态
				switch (status){
					case "S"://成功
						siteUserRecharge.setStatus(2);
						break;
					case "F"://失败
						siteUserRecharge.setStatus(3);
						break;
				}
				siteUserRecharge.setCallbackMsgConf(dataJson);
				siteUserRecharge.setRetMsgConf(message);
				siteUserRecharge.setRetCodeConf(code);
				SiteUserRechargeExample1 rechargeExample = new SiteUserRechargeExample1();
				rechargeExample.createCriteria().andIdEqualTo(siteUserRecharge.getId()).andOrderIdEqualTo(orderNo)
						.andInitialAmountEqualTo(totalRecharge).andAmountEqualTo(amount).andStatusEqualTo(1);
				siteUserRechargeMapper.updateByExampleSelective(siteUserRecharge,rechargeExample);
				// 4.判断是否充值成功 成功更新用户账户表
				if (2 == siteUserRecharge.getStatus()){
					siteUserAccount.setTotalRecharge(siteUserRecharge.getAmount().add(totalRecharge));
					siteUserAccount.setTotalAsset(siteUserRecharge.getAmount().add(siteUserAccount.getTotalAsset()));
					SiteUserAccountExample accountExample = new SiteUserAccountExample();
					accountExample.createCriteria().andUserIdEqualTo(siteUserRecharge.getUserId()).andTotalRechargeEqualTo(totalRecharge);
					siteUserAccountMapper.updateAccountExample(siteUserAccount,accountExample);
				}
			}else {
				log.info("金额不匹配---充值期初金额："+initialAmount +"累计充值金额："+totalRecharge);
				return null;
			}
		}catch (Exception e){
			log.info("处理业务逻辑失败");
			return null;
		}
		return "OK";
	}**/

	@Override
	public void rechargeQuery(SiteUserRecharge siteUserRecharge) {
		// TODO Auto-generated method stub
		
	}
}
